package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Leave;
import com.EAsystem.entity.Student;
import com.EAsystem.service.LeaveService;
import com.EAsystem.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class LeaveController {

    @Autowired
    private LeaveService leaveService;
    
    @Autowired
    private StudentService studentService;

    /**
     * 请假申请管理页面
     */
    @GetMapping("/leave")
    public String leavePage(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "10") int size,
                           @RequestParam(required = false) String studentName,
                           @RequestParam(required = false) Integer status,
                           Model model) {
        
        PageInfo<Leave> pageInfo;
        
        // 根据条件查询
        Leave searchLeave = new Leave();
        if (studentName != null && !studentName.trim().isEmpty()) {
            Student student = new Student();
            searchLeave.setStudent(student);
        }
        if (status != null) {
            searchLeave.setStatus(status);
        }
        
        if (studentName != null && !studentName.trim().isEmpty() || status != null) {
            pageInfo = leaveService.getLeavesByConditionWithPage(searchLeave, page, size);
        } else {
            pageInfo = leaveService.getAllLeavesWithPage(page, size);
        }

        PageInfo<Student> studentPageInfo = studentService.findAllByPage(1, 1000); // 获取足够多的学生
        List<Student> allStudents = studentPageInfo.getList();

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        model.addAttribute("leaves", pageInfo.getList());
        model.addAttribute("allStudents", allStudents);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchStudentName", studentName);
        model.addAttribute("searchStatus", status);
        model.addAttribute("pageNumbers", pageNumbers);
        
        return "admin/leave";
    }

    /**
     * 查看请假详情
     */
    @GetMapping("/leave/view/{id}")
    @ResponseBody
    public Map<String, Object> viewLeave(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Leave leave = leaveService.getLeaveById(id);
            if (leave != null) {
                result.put("success", true);
                result.put("leave", leave);
            } else {
                result.put("success", false);
                result.put("message", "请假记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取请假信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 审核请假申请
     */
    @PostMapping("/leave/approve/{id}")
    @ResponseBody
    public Map<String, Object> approveLeave(@PathVariable Integer id, 
                                           @RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (status != 1 && status != 2) {
                result.put("success", false);
                result.put("message", "审核状态无效");
                return result;
            }
            
            boolean success = leaveService.approveLeave(id, status);
            if (success) {
                result.put("success", true);
                result.put("message", status == 1 ? "审核通过" : "审核不通过");
            } else {
                result.put("success", false);
                result.put("message", "审核失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "审核失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除请假申请
     */
    @GetMapping("/leave/delete/{id}")
    public String deleteLeave(@PathVariable Integer id) {
        leaveService.deleteLeave(id);
        return "redirect:/admin/leave";
    }

    /**
     * 批量删除请假申请
     */
    @GetMapping("/leave/batchDelete")
    public String batchDeleteLeaves(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    leaveService.deleteLeave(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/leave";
    }

    /**
     * 搜索学生（用于AJAX）
     */
    @GetMapping("/leave/searchStudent")
    @ResponseBody
    public Map<String, Object> searchStudent(@RequestParam String studentName,
                                            @RequestParam(defaultValue = "1") int page,
                                            @RequestParam(defaultValue = "5") int size) {
        Map<String, Object> result = new HashMap<>();
        try {
            Leave searchLeave = new Leave();
            if (studentName != null && !studentName.trim().isEmpty()) {
                Student student = new Student();
                searchLeave.setStudent(student);
            }
            
            PageInfo<Leave> pageInfo = leaveService.getLeavesByConditionWithPage(searchLeave, page, size);

            if (studentName != null && !studentName.trim().isEmpty()) {
                pageInfo.getList().removeIf(leave -> 
                    leave.getStudent() == null || 
                    leave.getStudent().getUser() == null ||
                    leave.getStudent().getUser().getRealName() == null ||
                    !leave.getStudent().getUser().getRealName().contains(studentName.trim())
                );
            }
            
            result.put("success", true);
            result.put("leaves", pageInfo.getList());
            result.put("totalRecords", pageInfo.getTotal());
            result.put("totalPages", pageInfo.getPages());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索失败：" + e.getMessage());
        }
        return result;
    }
} 